//
//  MonthUpdateViewController.m
//  YellowBridge
//
//  Created by 王右 on 2018/12/4.
//  Copyright © 2018年 王右. All rights reserved.
//

#import "MonthUpdateViewController.h"
#import "ImagesAndContentTableViewCell.h"
#import "AttachListModel.h"
#import "PGDatePickManager.h"
#import "ProjectDeatailViewController.h"

@interface MonthUpdateViewController ()

@property (nonatomic, strong) NSDateComponents *dateComponents;

@property (weak, nonatomic) IBOutlet UITableView *baseTableView;
@property (strong, nonatomic) IBOutlet UITableViewCell *baseInfoCell;
@property (weak, nonatomic) IBOutlet UITextField *yearPlanMoneyTextField;
@property (weak, nonatomic) IBOutlet UITextField *sesionMoneyTextField;
@property (weak, nonatomic) IBOutlet UITextField *monthMoneTextFeild;
@property (weak, nonatomic) IBOutlet UITextField *completeMoneyTextField;
@property (weak, nonatomic) IBOutlet UIButton *selectTimeButton;


@property (strong, nonatomic) IBOutlet UITableViewCell *completeCell;
@property (weak, nonatomic) IBOutlet UIButton *completeButton;

@property (strong, nonatomic) IBOutlet UITableViewCell *bottomCell;

@property (nonatomic, strong) ImagesAndContentTableViewCell *progressCell;

@property (nonatomic, strong) ImagesAndContentTableViewCell *notesCell;

@property (strong, nonatomic) IBOutlet UITableViewCell *updateBottomCell;

@property (nonatomic, strong) NSMutableDictionary *parmDictionary;

@property (nonatomic, assign) BOOL isSelectStatus;

@end

@implementation MonthUpdateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSelectStatus = NO;

    _parmDictionary = @{@"account":User_Account,@"token":User_SignToken,@"pmid":_projectID}.mutableCopy;
    
    if (_dyModel.pmdone.length!=0) {
        [_completeButton setTitle:[_dyModel.pmdone isEqualToString:@"1"]?@"已竣工":@"未竣工" forState:(UIControlStateNormal)];
    }
    
    if (!_isUpdate) {
        self.title = @"月度更新";
        [_selectTimeButton setTitle:[NSString stringWithFormat:@"%@-%@",_dyModel.updateyear,_dyModel.updatemonth] forState:(UIControlStateNormal)];
        _yearPlanMoneyTextField.text = [NSString stringWithFormat:@"%@元", _dyModel.yearjhtze];
        _sesionMoneyTextField.text = [NSString stringWithFormat:@"%@元", _dyModel.quartertze];
        _monthMoneTextFeild.text = [NSString stringWithFormat:@"%@元", _dyModel.monthtze];
        _completeMoneyTextField.text = [NSString stringWithFormat:@"%@元", _dyModel.leijitze];
        [self getDyAttachInfo];
        _isSelectStatus=YES;
    }else{
        self.title = @"更新月度信息";
    }
    
    if (_isUpdate && _isMonthUpdate) {
        _yearPlanMoneyTextField.text = _dyModel.yearjhtze;
        _sesionMoneyTextField.text = _dyModel.quartertze;
        _monthMoneTextFeild.text = _dyModel.monthtze;
        _completeMoneyTextField.text = _dyModel.leijitze;
        [_selectTimeButton setTitle:[NSString stringWithFormat:@"%@-%@",_dyModel.updateyear,_dyModel.updatemonth] forState:(UIControlStateNormal)];
        [_completeButton setTitle:[_dyModel.pmdone isEqualToString:@"1"]?@"已竣工":@"未竣工" forState:(UIControlStateNormal)];
        _isSelectStatus = YES;
    }
    
    _progressCell = (ImagesAndContentTableViewCell *)[_baseTableView cellWithCellNibName:@"ImagesAndContentTableViewCell"];
    _notesCell = (ImagesAndContentTableViewCell *)[_baseTableView cellWithCellNibName:@"ImagesAndContentTableViewCell"];
    [self checkUserInterface];
}

- (void)getDyAttachInfo{
    [self hudWithText:@"获取附件信息中..."];
    [RequestManager postRequestWithModule:@"v1/dyattachlist" param:@{@"account":User_Account,@"token":User_SignToken,@"pmid":_projectID,@"dyid":_dyModel.dyID} model:nil success:^(NSDictionary *obj) {
        [self removeHud];
        NSArray *attachArr = [AttachListModel objectWithArray:obj[@"result"][@"atlist"]];
        [self configAttachArr:attachArr];
    } failure:^(NSString *error) {
        [self removeHud];
        [self.view makeToast:@"获取附件信息失败"];
    }];
}

- (void)configAttachArr:(NSArray *)attachArr{
    
    [attachArr enumerateObjectsUsingBlock:^(AttachListModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.attachtype isEqualToString:@"jd"]) {
            if (self->_dyModel.jdImageArr) {
                self->_dyModel.jdContent = obj.attachdesc;
                [self->_dyModel.jdImageArr addObject:obj.attachurl];
            }else{
                self->_dyModel.jdImageArr = [NSMutableArray array];
                [self->_dyModel.jdImageArr addObject:obj.attachurl];
                self->_dyModel.jdContent = obj.attachdesc;
            }
        }
        if ([obj.attachtype isEqualToString:@"bz"]) {
            if (self->_dyModel.notesImagesArr) {
                self->_dyModel.notesContent = obj.attachdesc;
                [self->_dyModel.notesImagesArr addObject:obj.attachurl];
            }else{
                self->_dyModel.notesImagesArr = [NSMutableArray array];
                [self->_dyModel.notesImagesArr addObject:obj.attachurl];
                self->_dyModel.notesContent = obj.attachdesc;
            }
        }
    }];
    [_baseTableView reloadData];
}


- (void)checkUserInterface{
    if (!_isUpdate) {
        _yearPlanMoneyTextField.userInteractionEnabled = NO;
        _monthMoneTextFeild.userInteractionEnabled = NO;
        _sesionMoneyTextField.userInteractionEnabled = NO;
        _completeMoneyTextField.userInteractionEnabled = NO;
        _completeButton.userInteractionEnabled = NO;
    }else{
        _yearPlanMoneyTextField.userInteractionEnabled = YES;
        _monthMoneTextFeild.userInteractionEnabled = YES;
        _sesionMoneyTextField.userInteractionEnabled = YES;
        _completeMoneyTextField.userInteractionEnabled = YES;
        _completeButton.userInteractionEnabled = YES;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            return 200;
            break;
        case 1:
            return [_progressCell returnCellHeight];
            break;
        case 2:
            return 60;
            break;
        case 3:
            return [_notesCell returnCellHeight];
        default:
            return 60;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            return _baseInfoCell;
            break;
        case 1:
            _progressCell.nameLabel.text = @"目前项目形象进度";
            if (!_progressCell.isContentReload) {
                _progressCell.imageArr = _dyModel.jdImageArr;
            }
            if (!_progressCell.textViewText) {
                _progressCell.textViewText = _dyModel.jddesc;
                if (_progressCell.textViewText.length == 0 && (_isUpdate == NO) ) {
                    _progressCell.textViewText = @"暂无项目进度描述";
                }
            }
            
            _progressCell.superTableView = tableView;
            if (!_isUpdate) {
                _progressCell.canEdit = NO;
            }else{
                _progressCell.canEdit = YES;
            }
            return _progressCell;
            break;
        case 2:
            return _completeCell;
            break;
        case 3:
            _notesCell.superTableView = tableView;
            _notesCell.nameLabel.text = @"备注说明";
            if (!_notesCell.isContentReload) {            
                _notesCell.imageArr = _dyModel.notesImagesArr;
            }
            if (!_notesCell.textViewText) {
                _notesCell.textViewText = _dyModel.contentdesc;
                if (_notesCell.textViewText.length == 0 && (_isUpdate == NO) ) {
                    _notesCell.textViewText = @"暂无项目备注描述";
                }
            }
            if (!_isUpdate) {
                _notesCell.canEdit = NO;
            }else{
                _notesCell.canEdit = YES;
            }
            return _notesCell;
        default:
            if (_isUpdate) {
                return _bottomCell;
            }else{
                return _updateBottomCell;
            }
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}


- (void)setIsUpdate:(BOOL)isUpdate{
    _isUpdate = isUpdate;
}

- (IBAction)completeButtonAction:(id)sender {
    __weak typeof(self) weakSelf = self;
    //项目状态（1-未竣工、2-已竣工）
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"请选择项目状态" buttonTitles:@[@"已竣工",@"未竣工"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
        if (index==0) {
            [weakSelf.parmDictionary setObject:@"1" forKey:@"pmdone"];
            [sender setTitle:@"已竣工" forState:(UIControlStateNormal)];
            self->_isSelectStatus = YES;
        }else if (index == 1){
            [weakSelf.parmDictionary setObject:@"0" forKey:@"pmdone"];
            [sender setTitle:@"未竣工" forState:(UIControlStateNormal)];
            self->_isSelectStatus = YES;
        }
    }];
    [sheet show];
}


- (IBAction)cancelButtonAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveButtonAction:(id)sender {
    if (_isMonthUpdate) {
        [self monthUpdateInfo];
    }else{
        NSDictionary *dymodel = @{@"projectid":_projectID}.mutableCopy;
        //每年计划投资总额
        if (_yearPlanMoneyTextField.text.length == 0) {
            [self.view makeToast:@"请输入每年计划投资额"];
            return;
        }else{
            [dymodel setValue:_yearPlanMoneyTextField.text forKey:@"yearjhtze"];
        }
        //季度完成投资额
        if (_sesionMoneyTextField.text.length == 0) {
            [self.view makeToast:@"请输入每季度投资额"];
            return;
        }else{
            [dymodel setValue:_sesionMoneyTextField.text forKey:@"quartertze"];
        }
        //月度完成投资额
        if (_monthMoneTextFeild.text.length == 0) {
            [self.view makeToast:@"请输入每月完成投资额"];
            return;
        }else{
            [dymodel setValue:_monthMoneTextFeild.text forKey:@"monthtze"];
        }
        //累计完成投资额(1年)
        if (_completeMoneyTextField.text.length == 0) {
            [self.view makeToast:@"请输入累计完成投资额"];
            return;
        }else{
            [dymodel setValue:_completeMoneyTextField.text forKey:@"leijitze"];
        }
        
        if (!_dateComponents) {
            [self.view makeToast:@"请选择更新日期"];
            return;
        }else{
            [dymodel setValue:[NSString stringWithFormat:@"%ld",_dateComponents.year] forKey:@"updateyear"];
            [dymodel setValue:[NSString stringWithFormat:@"%02ld",_dateComponents.month] forKey:@"updatemonth"];
        }
        if (!_isSelectStatus) {
            [self.view makeToast:@"请选择项目是否竣工!"];
            return;
        }
        
        [dymodel setValue:_parmDictionary[@"pmdone"]?:@"1" forKey:@"pmdone"];
        
        [dymodel setValue:_progressCell.textViewText.length==0?@"":_progressCell.textViewText forKey:@"jddesc"];
        
        [dymodel setValue:_notesCell.textViewText.length==0?@"":_notesCell.textViewText forKey:@"contentdesc"];
        
        [_parmDictionary removeObjectForKey:@"pmdone"];
        
        
        [_parmDictionary setValue:dymodel forKey:@"pmdymodel"];
        
        
        NSMutableArray *imageArr = [NSMutableArray array];
        if (_progressCell.imageArr.count != 0) {
            //添加环保参数
            for (NSString *imageString in _progressCell.imageArr) {
                NSDictionary *dic1 = @{@"attachurl":imageString,@"attachtype":@"jd",@"attachdesc":_progressCell.textViewText?:@""};
                [imageArr addObject:dic1];
            }
        }
        
        if (_notesCell.imageArr.count != 0) {
            for (NSString *imageString in _progressCell.imageArr) {
                NSDictionary *dic1 = @{@"attachurl":imageString,@"attachtype":@"bz",@"attachdesc":_notesCell.textViewText?:@""};
                [imageArr addObject:dic1];
            }
        }
        
        if (imageArr.count>0) {
            [_parmDictionary setValue:imageArr forKey:@"attachlist"];
        }else{
            [_parmDictionary setValue:[NSArray new] forKey:@"attachlist"];
        }
        
        [self hudWithText:@"项目信息上传中..."];
        [RequestManager postRequestWithModule:@"v1/savepmdy" param:_parmDictionary model:nil success:^(NSDictionary *obj) {
            [self removeHud];
            if ([obj[@"result"][@"check_result"] boolValue]) {
                [self.navigationController popViewControllerAnimated:YES];
                [[UIApplication sharedApplication].keyWindow makeToast:@"月度信息更新成功!"];
            }else{
                [self.view makeToast:obj[@"message"]];
            }
        } failure:^(NSString *error) {
            [self removeHud];
            [self.view makeToast:error];
        }];
    }
}

- (void)setDyModel:(ProjectDyListModel *)dyModel{
    if (dyModel) {
        _dyModel = dyModel;
    }
}

- (IBAction)updateButtonAction:(id)sender {
    if (User_IsManager) {
        MonthUpdateViewController *vc = [MonthUpdateViewController new];
        vc.dyModel = _dyModel;
        vc.projectID = _projectID;
        vc.isUpdate = YES;
        vc.isMonthUpdate = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self.view makeToast:@"您不是管理员,无权限修改此信息系!"];
    }
}
//更新月度更新信息
- (void)monthUpdateInfo{
    [self saveDyAttachInfo];
}

- (void)saveDyAttachInfo{
    NSDictionary *dymodel = @{@"projectid":_projectID}.mutableCopy;
    //每年计划投资总额
    if (_yearPlanMoneyTextField.text.length == 0) {
        [self.view makeToast:@"请输入每年计划投资额"];
        return;
    }else{
        [dymodel setValue:_yearPlanMoneyTextField.text forKey:@"yearjhtze"];
    }
    //季度完成投资额
    if (_sesionMoneyTextField.text.length == 0) {
        [self.view makeToast:@"请输入每季度投资额"];
        return;
    }else{
        [dymodel setValue:_sesionMoneyTextField.text forKey:@"quartertze"];
    }
    //月度完成投资额
    if (_monthMoneTextFeild.text.length == 0) {
        [self.view makeToast:@"请输入每月完成投资额"];
        return;
    }else{
        [dymodel setValue:_monthMoneTextFeild.text forKey:@"monthtze"];
    }
    //累计完成投资额(1年)
    if (_completeMoneyTextField.text.length == 0) {
        [self.view makeToast:@"请输入累计完成投资额"];
        return;
    }else{
        [dymodel setValue:_completeMoneyTextField.text forKey:@"leijitze"];
    }
    
    if (_dateComponents) {
        [dymodel setValue:[NSString stringWithFormat:@"%ld",_dateComponents.year] forKey:@"updateyear"];
        [dymodel setValue:[NSString stringWithFormat:@"%02ld",_dateComponents.month] forKey:@"updatemonth"];
    }else{
        [dymodel setValue:_dyModel.updateyear forKey:@"updateyear"];
        [dymodel setValue:_dyModel.updatemonth forKey:@"updatemonth"];
    }

    if ([_parmDictionary.allKeys containsObject:@"pmdone"]) {
        [dymodel setValue:_parmDictionary[@"pmdone"] forKey:@"pmdone"];
    }else{
        [dymodel setValue:_dyModel.pmdone forKey:@"pmdone"];
    }
    
    [dymodel setValue:_dyModel.dyID forKey:@"id"];
    
    [dymodel setValue:_progressCell.textViewText.length==0?@"":_progressCell.textViewText forKey:@"jddesc"];
    
    [dymodel setValue:_notesCell.textViewText.length==0?@"":_notesCell.textViewText forKey:@"contentdesc"];
    
    [_parmDictionary removeObjectForKey:@"pmdone"];
    
    [_parmDictionary setValue:dymodel forKey:@"pmdymodel"];
    
    [_parmDictionary removeObjectForKey:@"pmid"];
    
    [_parmDictionary setValue:_projectID forKey:@"projectid"];
    [self hudWithText:@"信息保存中"];
    [RequestManager postRequestWithModule:@"v1/updatepmdy" param:_parmDictionary model:nil success:^(NSDictionary *obj) {
        [self updateAttachInfo];
    } failure:^(NSString *error) {
        [self removeHud];
        [self.view makeToast:error];
    }];
};

- (void)updateAttachInfo{
    NSMutableDictionary *dic = @{@"account":User_Account,@"token":User_SignToken,@"projectid":_projectID,@"dyid":_dyModel.dyID}.mutableCopy;
    //添加进度参数
    NSMutableArray *jd = [NSMutableArray array];
    for (NSString *imageString in _progressCell.imageArr) {
        NSDictionary *dic1 = @{@"attachurl":imageString,@"attachtype":@"jd",@"attachdesc":_progressCell.textViewText?:@""};
        [jd addObject:dic1];
    }
    //添加备注参数
    for (NSString *imageString in _notesCell.imageArr) {
        NSDictionary *dic1 = @{@"attachurl":imageString,@"attachtype":@"bz",@"attachdesc":_notesCell.textViewText?:@""};
        [jd addObject:dic1];
    }
    
    [dic setValue:jd forKey:@"attachlist"];
    
    [RequestManager postRequestWithModule:@"v1/currsaveattach" param:dic model:nil success:^(NSDictionary *obj) {
        [self removeHud];
        if ([obj[@"result"][@"check_result"] boolValue]) {
            [[UIApplication sharedApplication].keyWindow makeToast:@"信息更新成功!"];
            [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[ProjectDeatailViewController class]]) {
                    [self.navigationController popToViewController:obj animated:YES];
                }
            }];
        }else{
            [self.view makeToast:@"信息更新失败,请重试!"];
        }
    } failure:^(NSString *error) {
        [self removeHud];
        [self.view makeToast:error];
    }];
}

- (IBAction)selectTimeButtonAction:(UIButton *)sender {
    if (!_isUpdate) {
        return;
    }
    //竣工时间
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.datePickerMode = PGDatePickerModeYearAndMonth;
    datePicker.selectedDate = ^(NSDateComponents *dateComponents) {
        NSLog(@"%ld-%ld-%ld",dateComponents.year,dateComponents.month,dateComponents.day);
        self->_dateComponents = dateComponents;
        [sender setTitle:[NSString stringWithFormat:@"%ld-%ld",dateComponents.year,dateComponents.month] forState:(UIControlStateNormal)];
    };
    [self presentViewController:datePickManager animated:false completion:nil];
}

@end
